Introduction
QR Codes are widely used for quick and easy access to websites, apps, and more. In this tutorial, we'll learn how to create a simple QR Code Generator using HTML, CSS, and JavaScript.
Step 1: Set Up HTML Structure
First, we need to set up the basic HTML structure for the QR Code Generator. Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>QR Code Generator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>QR Code Generator</h1>
<input type="text" id="qrText" placeholder="Enter text or URL" />
<button id="generateBtn">Generate QR Code</button>
<div id="qrCode"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Step 2: Styling with CSS
Next, we'll style the page with CSS to give it a clean look. Here's the CSS code:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, sans-serif;
}
body {
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
text-align: center;
background: #ffffff;
padding: 40px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
margin-bottom: 20px;
color: #333;
}
input {
width: 80%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
button {
padding: 10px 20px;
background-color: #e85c0d;
color: #fff;
border: none;
cursor: pointer;
border-radius: 5px;
margin-top: 10px;
}
#qrCode {
margin-top: 20px;
}
Step 3: Implementing JavaScript
Finally, we add JavaScript to handle QR code generation. Use the qrious
library to generate QR codes:
<script src="https://cdn.jsdelivr.net/npm/qrious@4.0.2/dist/qrious.min.js"></script>
document.getElementById('generateBtn').addEventListener('click', function() {
const qrText = document.getElementById('qrText').value;
if (qrText.trim() === "") {
alert("Please enter some text or URL to generate QR code");
return;
}
const qrCode = new QRious({
element: document.getElementById('qrCode'),
size: 200,
value: qrText
});
});
Step 4: Testing and Downloading QR Code
You can further enhance the project by adding a download button:
<button id="downloadBtn">Download QR Code</button>
document.getElementById('downloadBtn').addEventListener('click', function() {
const qrCodeCanvas = document.querySelector('#qrCode canvas');
const qrCodeImage = qrCodeCanvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = qrCodeImage;
link.download = 'qr-code.png';
link.click();
});